<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="top" style="padding: 0 30px">
    <p class="title">基础信息</p>
    <el-row>
      <el-col :span="12">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" size="small" placeholder="请输入" />
          <el-alert v-if="carTripsError" type="error" title="不能为0" show-icon />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" size="small" placeholder="请输入" />
          <el-alert v-if="carTripsError" type="error" title="不能为0" show-icon />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="是否启用" prop="status">
          <el-switch v-model="form.status" />
          <span style="margin-left: 10px; color: #a7a7a7">关闭后不在移动端显示</span>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-form-item label="内容" prop="content">
          <Editor v-model="form.content" :min-height="192" :height="300" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <div>
          <el-form-item label="上传封面" prop="coverUrl">
            <imageUpload
              v-model="form.coverUrl"
              :is-show-tip="false"
              :limit="1"
              :before-upload="beforeCoverUpload"
              @on-success="handleUploadSuccess"
              @on-remove="handleRemove"
            />
          </el-form-item>
        </div>
        <div class="el-upload__tip">支持扩展名：.png .jpg .jpeg；单个文件大小不超过50MB</div>
      </el-col>
      <el-col :span="12">
        <el-form-item label="上传文件" prop="completionMethod">
          <el-upload
            class="upload-demo"
            :action="uploadFileUrl"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleFileUploadSuccess"
            :on-change="handleChange"
            :file-list="fileList"
          >
            <el-button icon="el-icon-upload" size="small" type="primary" style="font-size: 14px">上传</el-button>
            <div slot="tip" class="el-upload__tip">
              文件类：支持 .rar .zip .doc .docx .pdf .jpg .jpeg .png；单个文件大小不超过50MB；
            </div>
            <div slot="tip" class="el-upload__tip">
              视频类：支持
              avi.wmv.mpeg.mp4.mov.mkv.flv.f4v.mdv.rmvb.rm.3gp.dat.ts.mts.vob等视频格式。大小请勿超过2G，请勿上传反动色情等违法视频。
            </div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-form-item>
      <div class="btn">
        <el-button class="button" @click="dialogVisible = false">取消</el-button>
        <el-button class="button" type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script>
import { getNewToken } from '@/utils/auth'
import beiGangApi from '@/api/logistics/beigang'
import Editor from '@/components/Editor/index'
export default {
  components: {
    Editor
  },
  data() {
    return {
      headers: {
        Authorization: 'Bearer ' + getNewToken()
      },
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/system/oss/upload',
      fileList: [],
      carTripsError: false, // 错误提示标志
      form: {
        status: true
      },
      rules: {
        distributionNode: [{ required: true, message: '请选择分配节点', trigger: 'change' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 封面上传前的校验
    beforeCoverUpload(file) {
      const isImage = ['image/png', 'image/jpeg'].includes(file.type)
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isImage) {
        this.$message.error('封面文件格式不正确，只支持 .png .jpg .jpeg')
        return false
      }
      if (!isLt50M) {
        this.$message.error('封面文件大小不能超过50MB')
        return false
      }
      return true
    },
    // 封面上传成功后的处理
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.$message.success('封面上传成功')
        // 提取 ossId 并赋值给 form.coverUrl
        const ossId = response.data.ossId
        this.form.coverUrl = ossId
        console.log(this.form.coverUrl)
      } else {
        this.$message.error(response.msg || '封面上传失败')
      }
    },
    // 处理封面删除
    handleRemove(file) {
      this.form.coverUrl = '' // 清除封面 URL
    },

    // 文件上传前的校验
    beforeUpload(file) {
      console.log('File Type:', file.type)
      const isValidType =
        [
          'application/zip',
          'application/x-zip-compressed',
          'application/x-rar-compressed',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/msword',
          'application/pdf',
          'image/jpeg',
          'image/png'
        ].includes(file.type) || ['video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-msvideo'].includes(file.type)
      const isLt50M = file.size / 1024 / 1024 < 50
      const isLt2G = file.size / 1024 / 1024 < 2000

      if (!isValidType) {
        this.$message.error('文件格式不正确')
        return false
      }
      if (file.type.startsWith('video/') && !isLt2G) {
        this.$message.error('视频文件大小不能超过2G')
        return false
      }
      if (!file.type.startsWith('video/') && !isLt50M) {
        this.$message.error('文件大小不能超过50MB')
        return false
      }
      return true
    },
    // 文件上传成功后的处理
    handleFileUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('文件上传成功')

        // 提取 ossId 并按指定格式保存到 form.helpFileList 中
        const ossId = response.data.ossId // 假设返回的响应中有 ossId 字段
        if (!this.form.helpFileList) {
          this.form.helpFileList = [] // 初始化 helpFileList 数组
        }
        this.form.helpFileList.push({ ossId }) // 将 ossId 保存到 helpFileList

        // 更新显示的文件列表
        this.fileList = fileList
      } else {
        this.$message.error(response.msg || '文件上传失败')
      }
    },
    // 处理文件删除
    handleFileRemove(file, fileList) {
      const index = this.form.helpFileList.findIndex((item) => item.fileName === file.name)
      if (index !== -1) {
        this.form.helpFileList.splice(index, 1) // 从 helpFileList 中移除
      }
      // 更新文件列表
      this.fileList = fileList
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    validatePlanFloatRate() {
      const value = this.form.planFloatRate
      const regex = /^\d{0,3}(\.\d{0,2})?$/ // 正则匹配：最多3位整数和2位小数
      if (!regex.test(value)) {
        this.form.planFloatRate = value.slice(0, -1) // 通过截取字符串来限制不合法输入
      }
    },

    checkPlanFloatRate(rule, value, callback) {
      const regex = /^\d{1,3}(\.\d{1,2})?$/ // 匹配1~3位整数和最多2位小数
      if (value === '' || value === null) {
        callback(new Error('请输入计划量上浮比例'))
      } else if (!regex.test(value)) {
        callback(new Error('请输入合法的数值，最多3位整数和2位小数'))
      } else {
        callback()
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const formData = {
            helpTypeId: '1844262695854039041',
            title: this.form.title,
            orderNum: this.form.orderNum,
            status: this.form.status ? '0' : '1', // 转换状态值为 '0' (启用) 或 '1' (禁用)
            content: this.form.content,
            coverUrl: this.form.coverUrl[0].ossId,
            helpFileList: this.form.helpFileList
          }
          console.log(formData)
          beiGangApi
            .addHelpCenter(formData)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success('新增成功')
                this.$refs.form.resetFields()
                this.$router.push({ path: '/logistics/beiGang/helpCenter' })
              } else {
                this.$message.error(res.msg || '操作失败')
              }
            })
            .catch((error) => {
              this.$message.error('新增失败: ' + error.message)
            })
        } else {
          this.$message.error('填写错误，请修改后再提交')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input {
  width: 90%;
}
::v-deep .el-input-group__append {
  background-color: #fff;
}
::v-deep .el-form-item__content {
  // line-height: normal;
}
.title {
  font-size: 16px;
  font-weight: 700;
}
.input {
  margin: 0 8px;
  width: 15%;
}
.text {
  line-height: 32px;
}
.btn {
  position: fixed;
  bottom: 20px;
  right: 40px;
  display: flex;
  justify-content: flex-end;

  .button {
    margin-left: 10px;
    width: 80px;
  }
}
.el-upload__tip {
  margin-top: 0;
  color: #999999;
  line-height: 20px;
}
// .btn {
//   display: flex;
//   justify-content: flex-end;
//   .button {
//     margin-top: 30px;
//     width: 80px;
//   }
// }
</style>
